package service.impl;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import pojo.CommandData;
import pojo.ImageSource;
import pojo.LocalImage;
import service.ImageService;
import util.CollectionRandomUtil;
import util.ImageProcessUtil;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

// TODO 这个网站的图片其实也有分类，这里先暂时不做，以后有空再做

/**
 * WallpaperAbyss页面链接：
 * <a href="https://wall.alphacoders.com/by_sub_category.php?id=207050&name=%E6%98%9F%E9%99%85%E4%BA%89%E9%9C%B82+%E5%A3%81%E7%BA%B8&lang=Chinese">壁纸</a>
 */
public class WallpaperAbyssImageServiceImpl implements ImageService {
	public static final WallpaperAbyssImageServiceImpl INSTANCE = new WallpaperAbyssImageServiceImpl();
	/** 图片爬取的根地址 */
	public static final String BASEURL = "https://wall.alphacoders.com/by_sub_category.php";

	private WallpaperAbyssImageServiceImpl() {
	}

	@Override
	public List<ImageSource> getImageDownloadLink(CommandData command) throws IOException {
		System.out.println("WallpaperAbyssImageServiceImpl.getImageDownloadLink()");
		Document document = Jsoup.connect(BASEURL)
				.data("id", "207050")
				.data("name", "星际争霸2+壁纸")
				.data("lang", "Chinese")
				.ignoreContentType(true)
				.timeout(100000)
				.get();

		List<ImageSource> res = document.select(".img-responsive.thumb-desktop")
				.parallelStream()
				.map(e -> {
					String imageUrl = e.attr("src");
					// 这里去掉后缀
					String filename = imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.lastIndexOf("."));
					return new ImageSource(filename, filename, imageUrl);
				})
				.collect(Collectors.toList());

		return CollectionRandomUtil.randomOrder(res, command.getCount());
	}

	@Override
	public List<LocalImage> downloadImage(CommandData command, List<ImageSource> imageSources) {
		return imageSources.parallelStream()
				.map(imageUrl -> {
					String id = imageUrl.getId();
					// 先检查本地是否已有该图片，这里文件名是ID
					String filePath = ImageProcessUtil.checkLocalImage(id);
					if (filePath != null)
						return new LocalImage(filePath, imageUrl);

					// 下载该图片
					String suffix = ImageProcessUtil.getImageSuffixByUrl(imageUrl.getDownloadLink());
					filePath = SAVE_PATH + "/" + id + "." + suffix;
					try {
						ImageProcessUtil.imageDownload(imageUrl.getDownloadLink(), filePath);
						return new LocalImage(filePath, imageUrl);
					} catch (IOException | RuntimeException e) {
					}
					return null;
				})
				.filter(Objects::nonNull) //过滤掉失败的
				.collect(Collectors.toList());
	}

	@Override
	public Map<String, String> getSortMap() {
		return null;
	}
}
